#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@File: amlEvnView.py
@Author: lijk34925 
@Date: 2024/8/16 15:55
@desc: 环境检查相关路由操作
"""
import shutil
import threading
import traceback
from copy import deepcopy
from datetime import datetime

from fastapi import APIRouter, Form, Header, Depends, UploadFile, File

from AmlScripts.amlConfig import amlConfig
from AmlScripts.BasicFunction.env_check import change_company, check_server
from BladeFerm.utils.basic_opration import is_dir_exist, clear_dir
from BladeFerm.utils.dataoperation import YamlOperation
from DataTest.tabledata.commonData.generatedData import generated_data
from DataTest.util.logCheck import detect_errors
from BladeFerm.Lib.Common import logger
from BladeFerm.Lib.Common import logFile
from Models.ApiParams import DingMessage, EnvCheckParams
from uploadBladeCase.ReadLoaclConfig import get_excel_content, import_sql_files, unzip_file, tip_ding
from uploadBladeCase.ReadLoaclConfig import download_and_compare_zip
from BladeFerm.utils.http_opration import DingRebot

from uploadBladeCase.RemoteSSHClient import RemoteSSHClient

router = APIRouter()

company_no_list = get_excel_content("./static/AmlConfig/反洗钱5.0客户版本统计.xlsx",
                                    "./static/AmlConfig/Aml5_company_list.json")


async def get_header_info(userNo: str = Header(None)):
    return {"userNo": userNo}


@router.post("/dingMsg")
async def send_ding_message(msg: DingMessage):
    message = f"{msg.title}\n{msg.message}"
    res = tip_ding(message)
    return {'result': True, 'status': 'success', 'data': res, 'message': message}


@router.get("/getDataBases/")
async def get_databases():
    result = list(amlConfig.keys())
    if 'env' in result:
        result.remove('env')
    config_bak = dict()
    env_list = list()
    for unit in result:
        env_config = amlConfig.get(unit)
        env_ip = env_config.get('machine').get("ip", "None")
        title = env_config.get("title") + "_" + env_ip
        env_list.append({"name": unit, "title": title})
        config_bak[title] = deepcopy(env_config)
    return {'result': env_list, 'data': config_bak, 'list': company_no_list,
            'status': 200, 'message': '获取数据库类型成功！'}


@router.post("/compareZip/")
async def compare_zip(
        name: str = Form(...),
        raw: str = Form(...),
        target: str = Form(...)
):
    t = threading.Thread(target=download_and_compare_zip, args=(name, raw, target,))
    t.start()
    message = "开始比对zip包，请稍后查看钉钉通知！"
    return {'result': True, 'status': 'success', 'data': message, 'message': message}


@router.post("/importSql/")
async def upload_and_importSql(
        env: str = Form(...),
        user: str = Form(...),
        sqlZip: UploadFile = File(...)
):
    # 步骤1：保存文件
    current_time = datetime.now()
    formatted_time = current_time.strftime("%Y%m%d%H%M%S")
    base_dir = ".\\static\\sql"
    sql_temp_dir = ".\\static\\sql\\temp"
    is_dir_exist(base_dir)
    is_dir_exist(sql_temp_dir)
    file_path = base_dir + "\\" + formatted_time + '_' + sqlZip.filename
    with open(file_path, "wb") as buffer:
        shutil.copyfileobj(sqlZip.file, buffer)
    logger.info(f"upload file successful! filePath: {file_path}")
    # 步骤2：文件解压
    exitFlag = clear_dir(sql_temp_dir)
    if exitFlag:
        unzip_file(file_path, sql_temp_dir)
        # 步骤3：调用导入sql文件方法
        t = threading.Thread(target=import_sql_files, args=(env, sql_temp_dir, user,))
        t.start()
        message = "开始批量导入SQL！"
        return {'result': True, 'status': 'success', 'data': message, 'message': message}
    else:
        error = f'{sql_temp_dir} 目录清理失败，请检查！'
        return {'result': False, 'status': 'failed', 'data': error, 'message': error}


@router.post("/changeNo/")
async def chang_company_no(
        header: dict = Depends(get_header_info),
        name: str = Form(...),
        env: str = Form(...),
        company_no: str = Form(...),
        company_name: str = Form(...),
):
    if not env or not company_no or not company_name:
        return {'result': True, 'status': "failed", 'message': '入参不全，请检查！'}
    config = YamlOperation("./config/金融反洗钱项目.yaml").readYaml()
    env_config = config.get('env')
    user_no = header.get('userNo')
    user_no_2 = name if name else user_no
    env_name = amlConfig.get(env).get('title', 'Undefined')
    message = f"环境：{env_name}，开始切换公司号：{company_no}，公司名称：{company_name}，操作用户：{user_no_2}"
    logger.info(f"{message}， {env_config}")
    ding_url = env_config.get('dingApiKey', None)
    DingRebot(ding_url).post(message, [], isAtAll=True)
    t = threading.Thread(target=change_company, args=(company_no, company_name, env, ding_url))
    t.start()
    return {'result': True, 'status': 'success', 'message': '切换公司号成功！开始重新导入指标和规则，间隔1min后查看日志！'}


@router.get("/checkEnvironment/")
async def check_environment(env: str, is_sync: int = 0):
    if not env:
        return {'result': True, 'status': "failed", 'message': '缺少入参，请检查！'}
    if is_sync:
        result = check_server(env)
        return {'result': result, 'status': 'success',  'message': f'获取环境检查最终的结果为：{result}！'}
    else:
        t = threading.Thread(target=check_server, args=(env, ))
        t.start()
        return {'result': True, 'status': 'success', 'message': '开始逐个检查服务，异常服务会自动重启！间隔1min后查看日志！'}


@router.post("/checkLog/")
async def check_log(env: str = Form(...), server: str = Form(...),):
    if not env or (not server):
        return {'result': True, 'status': "failed", 'message': '缺少入参，请检查！'}
    content = detect_errors(server, env)
    return {'result': True, 'status': 'success', 'message': '日志查看成功！', 'content': content}


@router.post("/checkMachineUsed")
async def check_machine_used(params: EnvCheckParams):
    if not params.envs:
        return {'result': True, 'status': "failed", 'message': '缺少入参，请检查！'}
    # 执行检查和清理动作
    SSHClient = RemoteSSHClient(amlConfig)
    t = threading.Thread(target=SSHClient.batch_check_task, args=(params.envs, params.limit,))
    t.start()
    return {
        'result': True,
        'status': 'success',
        'message': f'开始为{len(params.envs)}个环境做资源校验和清理历史安装包的操作，稍后刷新日志查看！'
    }


@router.get("/queryEnvLog/")
async def query_environment(row: int = 0):
    with open(logFile, mode='r', encoding='utf-8') as f:
        lines = f.readlines()
        content = lines[row:]
    return {'result': content, 'status': 200, 'message': f'获取最新的{row}行日志成功！'}


@router.post("/mockData/")
async def mock_data(env: str = Form(...), description: str = Form(...),):
    if (not env) or (not description):
        return {'result': True, 'status': "failed", 'message': '缺少入参，请检查！'}
    content = ""
    try:
        result = generated_data(description, env)
        content = f"客户号：{result} ，生成模拟数据并插入数据库成功！"
        return {'result': True, 'status': 'success', 'message': '数据模拟成功！', 'content': [content]}
    except Exception:
        content += traceback.format_exc()
        logger.error(content)
        return {'result': False, 'status': 'fail', 'message': '数据模拟失败！', 'content': [content]}
